﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Globalization;
using Iesi.Collections.Generic;
using Spring.Objects;
using System.Reflection;
using Spring.Core;
using Microsoft.VisualBasic;

/// <summary>
/// ConvertUtil 的摘要描述
/// </summary>
/// 

namespace com.pro2e.console.core.util
{
    public class ConvertUtil
    {
        public ConvertUtil()
        {
        }

        /// <summary>
        /// 轉換字串yyyy/mm/dd日期至日期格式，若字串為空則傳回null
        /// </summary>
        /// <param name="dateStr">日期的字串型態</param>
        /// <returns>回傳日期</returns>
        public static DateTime? ConvertStringToDate(string dateStr)
        {
            if (string.IsNullOrEmpty(dateStr))
            {
                return null;
            }
            else
            {
                return ToDateTime(dateStr);
            }
        }


        public static int ConvertDecimalToInt(Decimal d)
        {
            int a = (int)d;

            return a;
        }

        public static string ConvertDecimalToIntStr(Decimal d)
        {
            int a = (int)d;

            return a.ToString();
        }


        /// <summary>
        /// 將字串轉為數字，若null則傳回0
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static int ConvertStringToInt(string p)
        {
            return (string.IsNullOrEmpty(p) ? 0 : int.Parse(p));
        }


        public static bool IsNumber(string strNumber)
        {
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"^-?\d+(\.)?\d*$");
            return r.IsMatch(strNumber);
        }


        /// <summary>
        /// 將日期轉為yyyy/mm/dd的格式
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string ConvertDateToStr(DateTime? date)
        {
            if (date == null)
            {
                return "";
            }
            else
            {
                return (ConvertUtil.DateToShortDateStr(date));
            }
        }

        /// <summary>
        /// 將日期轉為yyyy/mm/dd hh:mm:ss的格式
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string ConvertDateToAllStr(DateTime? date)
        {
            if (date == null)
            {
                return "";
            }
            else
            {
                return (DateToShortDateStr(date.Value) + " " + DateToShortTimeStr(date.Value));
            }
        }

        /// <summary>
        /// 將日期轉為yyyy/mm/dd的字串
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string DateToShortDateStr(DateTime? date)
        {
            return DateToShortDateStr(date, "/");
        }

        /// <summary>
        /// 將日期轉為yyyy/mm/dd的字串
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string DateToShortDateStr(DateTime? date,string separator)
        {
            if (date == null)
            {
                return "";
            }
            else
            {
                return (string.Format(date.Value.ToString("yyyy{0}MM{1}dd"), separator, separator));
            }
        }

        /// <summary>
        /// 將日期轉為hh/mm/ss的時間
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string DateToShortTimeStr(DateTime? date)
        {
            if (date == null|| date.Value==null)
            {
                return "";
            }
            else
            {
                return (date.Value.ToString("HH:mm:ss"));
            }
        }


        public static object CloneObject(object obj)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter(null,
            new StreamingContext(StreamingContextStates.Clone));

            bf.Serialize(ms, obj);
            ms.Position = 0;
            Object res = bf.Deserialize(ms);
            ms.Close();
            return res;
        }


        /// <summary>
        /// 無條件捨去取整個
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static int Floor(double p)
        {
            return ((int)Math.Floor(Convert.ToDouble(p.ToString())));
        }


        /// <summary>
        /// 將yyyy/mm/dd轉換為Datetime格式
        /// </summary>
        /// <param name="dateTimeStr"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(string dateTimeStr)
        {
            return ToDateTime(dateTimeStr, '/');
        }

        /// <summary>
        /// 將yyyy/mm/dd轉換為Datetime格式
        /// </summary>
        /// <param name="dateTimeStr"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(string dateTimeStr,char separator)
        {
            string[] strArray = dateTimeStr.Split(separator);

            DateTime d = new DateTime(Convert.ToInt32(strArray[0]), Convert.ToInt32(strArray[1]), Convert.ToInt32(strArray[2]));
            return d;
        }


        /// <summary>
        /// 轉換成完整的日期字串 yyyy/mm/dd hh:MM:ss
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string ToShortDateTimeStr(DateTime? date)
        {
            if (date.HasValue)
            {
                DateTime tmp = date.Value;
                return DateToShortDateStr(tmp) + " " + DateToShortTimeStr(tmp);
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 傳回當天日期最後的時間例如1月1日23:59:59
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static DateTime ToDateTimeMax(DateTime dateTime)
        {
            DateTime tmp = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59);
            return tmp;
        }

        /// <summary>
        /// 傳回當天日期最早的時間例如1月1日00:00:00
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static DateTime ToDateTimeMin(DateTime dateTime)
        {
            DateTime tmp = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
            return tmp;
        }

        /// <summary>
        /// 將int轉換為字串數字格式(#,##0)
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string ToIntNumberStr(int num)
        {
            NumberFormatInfo myNfi = new NumberFormatInfo();
            myNfi.NumberNegativePattern = 1;
            myNfi.NumberDecimalDigits = 0;
            
            return num.ToString("N", myNfi);
            //return num.ToString("#,##0");
        }

        public static int ToInt32(string p)
        {
            if (!string.IsNullOrEmpty(p)&&IsNumber(p))
            {
                return Convert.ToInt32(p);
            }
            else
            {               
                return 0;
            }
        }


        internal static double ToDouble(string p)
        {
            if (!string.IsNullOrEmpty(p) && IsNumber(p))
            {
                return Convert.ToDouble(p);
            }
            else
            {
                return 0;
            }          
        }

        public static string ToIntNumberStr(decimal p)
        {
            return (ToIntNumberStr(Convert.ToInt32(p)));
        }

        /// <summary>
        /// 四捨五入取至整數
        /// </summary>
        /// <param name="noTaxNum"></param>
        /// <returns></returns>
        public static int ToRoundInt(double num)
        {

            return (Convert.ToInt32(Math.Round(num, 0, MidpointRounding.AwayFromZero)));
        }


        /// <summary>
        /// 四捨五入取至整數然後以#,##0格式呈現
        /// </summary>
        /// <param name="noTaxNum"></param>
        /// <returns></returns>
        public static string ToRoundIntStr(double num)
        {
            return ToRoundInt(num).ToString("#,##0");
        }


        /// <summary>
        /// 將null轉換為空字串
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string ConvertNull(string p)
        {
            if (p == null)
            {
                return "";
            }
            else 
            {
                return p;
            }
        }

        public static T[] SetToArray<T>(Set<T> set)
        {
            return (set.ToArray<T>());
        }

        /// <summary>
        /// 將來源物件的所有欄位值複製一份至目標物件
        /// </summary>
        /// <param name="sourceObj">來源物件</param>
        /// <param name="targetObj">目標物件</param>
        public static void CopyFieldValue(Object sourceObj, Object targetObj)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            if (sourceObj == null || targetObj == null) 
            {
                return;
            }

            ObjectWrapper owSource = new ObjectWrapper(sourceObj);
            ObjectWrapper owTarget = new ObjectWrapper(targetObj);
            
            foreach (PropertyInfo proInfo in sourceObj.GetType().GetProperties())
            {
                string fieldName = proInfo.GetGetMethod().Name.Replace("get_", "");
                if (HasProperty(owTarget, fieldName))
                {
                    owTarget.SetPropertyValue(fieldName, owSource.GetPropertyValue(fieldName));
                }
            }            
        }


        /// <summary>
        /// 轉全形
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToHolomorphic(string str)
        {
            return Strings.StrConv(str, VbStrConv.Wide, 0);
        }

        /// <summary>
        /// 轉半形
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToHalf(string str)
        {
            return Strings.StrConv(str, VbStrConv.Narrow, 0);
        }

        /// <summary>
        /// 取得附檔名
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string GetExtName(string p)
        {
            if (!string.IsNullOrEmpty(p))
            {
                int index = p.LastIndexOf(".");
                if (index != -1)
                {
                    return (p.Substring(index, p.Length - index));
                }
            }
                return "";            
        }

        #region private method
        private static bool HasProperty(ObjectWrapper ow, string fieldName)
        {
            try
            {
                object value = ow.GetPropertyValue(fieldName);
                return true;
            }
            catch (InvalidPropertyException)
            {
                return false;
            }
        }
        #endregion



        /// <summary>
        /// 將物件toString
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string ConvertNULL(object p)
        {
            if (p == null)
            {
                return "";
            }
            else
            {
                return p.ToString().Trim();
            }
        }
    }
}